import api from "@/api/api";
import {
  CUSTOMER_INFO,
  MERCHANT_INFO,
  USER_SPECICAL_INFO,
  USER_INFO,
} from "@/utils/constant";
import tip from "@/utils/tip";
import commonFunction from "@/utils/commonFunction.js";
import commonSensors from "@/utils/commonSensors.js";
import md5 from "@/utils/md5.js";
import {
  REGISTER_USER_TYPE,
  MESSAGE_MODAL_NO_MATCHING_CODE,
  MESSAGE_MODAL_SUCCESS_CODE,
} from "./static";

// 导航去 爱丁顿个人信息保护政策
export const navigateToProtectionPolicy = () => {
  uni.navigateTo({
    url: "/pages/utcms/utcms?uttype=protectionPolicy",
  });
};
// 是否同意爱丁顿个人信息保护政策
export const checkPolicy = async (jwt) => {
  let result;
  try {
    const json = await api.getPolicyStatus({
      method: 'GET',
      header: {
        jwt: jwt
      },
      query: {
        name: 'privacyPolicy',
        version: 'v1.2'
      }
    })
    if (json.code == 1000) {
      result = json.data.isAgreed
      return result
    } else {
      result = 'No'
      return 'No'
    }
  } catch (error) {

  }
};

// 导航去 THE MACALLAN SOCIETY会员规则
export const navigateToMemberRule = () => {
  uni.navigateTo({
    url: "/pages/cms/page?identifier=cms/memberRule",
  });
};

// 解密手机号
export const getPhoneNumberData = async (getPhoneNumberEv, noTips = false) => {
  const result = {
    success: false,
    ERROR_CODE: "",
    data: null,
  };
  try {
    const {
      encryptedData,
      iv
    } = getPhoneNumberEv.detail;
    if (encryptedData && iv) {
      const userInfo = uni.getStorageSync(USER_INFO) || "";
      const accountInfo = uni.getAccountInfoSync();
      const appId = accountInfo.miniProgram.appId;
      const userSpecialInfo = uni.getStorageSync("userSpecialInfo");
      const res = await api.getUserPhoneNumber({
          method: "GET",
          query: {
            encrypted_data: encryptedData,
            iv: iv,
            open_id: userInfo.openid || userSpecialInfo.openid,
          },
        },
        appId
      );
      if (res.code === 1000) {
        result.success = true;
        result.data = res.data;
      } else {
        result.ERROR_CODE = "API_ERROR";
      }
    } else {
      result.ERROR_CODE = "CANCEL";
      if (!noTips) {
        tip.plainText("已拒绝获取手机号");
      }
    }
  } catch (error) {
    // console.error("in getPhoneNumberData error:", error);
    result.ERROR_CODE = "ERROR";
  }

  return result;
};

// 更新隐私条款
export const updatePolicyStatus = async () => {
  try {
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    if (customerInfo.jwt) {
      const res = await api.setPolicyStatus({
        method: "PUT",
        header: {
          jwt: customerInfo.jwt,
        },
        query: {
          isAgreed: "Yes",
          name: "privacyPolicy",
          version: "v1.2",
        },
      });
      if (res.code === 1000) {
        uni.setStorageSync("isAgreePolicy", "Yes");
      }
    }
  } catch (error) {
    // console.error("updatePolicyStatus error:", error);
  }
};

export const getTsInfoNoLogin = async (tsActId) => {
  const result = {
    success: false,
    data: null,
  };
  try {
    const merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    const res = await api.getTsInfoNoLogin({
        method: "GET",
        query: {
          merchant_id: merchantInfo.cloudMerchantId,
        },
      },
      tsActId
    );
    if (res.code === 1000) {
      result.success = true;
      result.data = res.data;
    }
  } catch (error) {
    // console.error("in getTsInfoNoLogin error:", error);
  }

  return result;
};

// 通过活动id获取ts活动信息
export const getTsProcessStatus = async (tsActId) => {
  const result = {
    tsActId,
    path: "",
    success: false,
  };
  let messageModalCode = MESSAGE_MODAL_NO_MATCHING_CODE;
  try {
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
    let memberDetails = uni.getStorageSync("memberDetails");
    const query = {
      store_id: merchantInfo.cloudMerchantStoreId,
      group_id: customerInfo.groupId,
      member_level_id: memberDetails.memberLevelId,
    };
    const res = await api.getTsById({
        header: {
          jwt: customerInfo.jwt,
        },
        method: "GET",
        query,
      },
      tsActId
    );
    if (res.code == 1000) {
      result.success = true;
      let {
        status
      } = res.data;
      if (status == -2) {
        // 未邀请
        messageModalCode = "EVENT_NOT_INVITED_MEMBER";
      } else if (status == 7 || status == 9) {
        // 已结束
        messageModalCode = "EVENT_HAS_ENDED";
      } else if (status == 4) {
        // 未开始
        messageModalCode = "EVENT_NOT_STARTED";
      } else if (status == 5 || status == 6) {
        // 活动可以加入
        messageModalCode = MESSAGE_MODAL_SUCCESS_CODE;
        result.path = `/pages/special/specialSale?tsActId=${tsActId}`;
      }
    }
  } catch (error) {
    // console.error("getTsProcessStatus error:", error);
  }
  result.messageModalCode = messageModalCode;
  return result;
};
// 通过手机号获取ts活动信息
export const getTsByPhoneNumber = async (phoneNumber, tsActId) => {
  const result = {
    status: "",
    invited: false,
  };
  try {
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
    const query = {
      store_id: merchantInfo.cloudMerchantStoreId,
      merchant_id: merchantInfo.cloudMerchantId,
      mobile: phoneNumber,
    };
    const res = await api.getTsByPhoneNumber({
        method: "GET",
        query,
      },
      tsActId
    );
    if (res.code === 1000) {
      result.invited = res.data.invited;
      result.tsStatus = res.data.status;
    } else {
      // 无可参与的活动 走正常注册逻辑
      result.invited = false;
    }
  } catch (error) {
    // console.error("getTsByPhoneNumber error:", error);
  }
  return result;
};

// 通过手机号获取union-id
export const getUnionByPhone = async (phoneNumber) => {
  const result = {
    phoneNumber: md5.hex_md5(phoneNumber),
    phoneSuccess: false,
  };
  try {
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
    const query = {
      merchant_id: merchantInfo.cloudMerchantId,
    };
    const res = await api.getUnionByPhone({
        method: "GET",
        query,
      },
      phoneNumber
    );
    if (res.code === 1000) {
      // 1000 说明是会员
      result.phoneSuccess = true;
    } else if (res.code === -1001) {
      result.phoneSuccess = false;
    }
  } catch (error) {
    // console.error("getUnionByPhone error:", error);
  }
  return result;
};

// 通过union-id获取手机号
export const getPhoneByUnion = async () => {
  let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
  let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
  const result = {
    getPhoneNumber: "",
    unionSuccess: false,
  };
  try {
    const query = {
      merchant_id: merchantInfo.cloudMerchantId,
    };
    const res = await api.getPhoneByUnion({
        method: "GET",
        query,
      },
      userSpecialInfo.unionId
    );
    if (res.code === 1000) {
      // 有 encryptMobile  说明当前union-id 有手机号
      result.getPhoneNumber = res.data.encryptMobile || "";
      result.unionSuccess = true;
    } else {
      result.unionSuccess = false;
    }
  } catch (error) {
    // console.error("getPhoneByUnion error:", error);
  }
  return result;
};

/**
 *正常注册
 * @param {*} phone 手机号
 * @param {*} type REGISTER_USER_TYPE: OLD_USER(老会员) | NEW_USER(新会员)
 * @returns
 */
export const getCommonStatus = async (phone, type) => {
  let messageModalCode = MESSAGE_MODAL_NO_MATCHING_CODE; // 没有匹配下面任何一项
  const tmp = {
    type,
  };

  try {
    let getInfoByPhoneNumber = await getUnionByPhone(phone);
    let getInfoByUnionId = await getPhoneByUnion();
    tmp.getUnionByPhoneData = getInfoByPhoneNumber;
    tmp.getInfoByUnionIdData = getInfoByUnionId;
    let {
      phoneNumber,
      phoneSuccess
    } = getInfoByPhoneNumber;
    let {
      getPhoneNumber,
      unionSuccess
    } = getInfoByUnionId;
    if (type === REGISTER_USER_TYPE.OLD_USER) {
      // 我是老会员
      if (!phoneSuccess && !unionSuccess) {
        // 不是老会员
        messageModalCode = "NONE";
      } else if (
        !phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        //授权手机号非会员，union-id有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NOT_MEMBER";
      } else if (
        phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        // 授权手机号是会员，union-id有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NO_ID";
      } else if (
        !unionSuccess ||
        !getPhoneNumber ||
        (unionSuccess && getPhoneNumber == phoneNumber)
      ) {
        // union-id没有手机号 或 union-id有手机号且手机号和授权手机号一致
        messageModalCode = "SUCCESS_BIND";
      }
    } else {
      // 立即加入是新会员
      if (!phoneSuccess && !unionSuccess) {
        messageModalCode = "SUCCESS_JOIN";
      } else if (
        !unionSuccess ||
        !getPhoneNumber ||
        (unionSuccess && getPhoneNumber == phoneNumber)
      ) {
        // union-id没有手机号 或 union-id有手机号且手机号和授权手机号一致
        messageModalCode = "SUCCESS_BIND_HAS_MEMBER";
      } else if (
        !phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        //授权手机号非会员，union-id有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NOT_MEMBER";
      } else if (
        phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        // 授权手机号是会员，union-id有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NO_ID";
      }
    }
  } catch (error) {
    // console.error("getCommonStatus error:", error);
  }
  const result = {
    ...tmp,
    messageModalCode,
  };
  return result;
};

// ts注册状态弹窗
export const getTargetSaleStatus = async (phone, tsActId) => {
  let messageModalCode = MESSAGE_MODAL_NO_MATCHING_CODE;
  const tmp = {
    phoneNumber: phone,
    tsActId,
    canRegister: false,
  };
  try {
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let getInfoByPhoneNumber = await getUnionByPhone(phone);
    let getInfoByUnionId = await getPhoneByUnion();
    let tsInfo = await getTsByPhoneNumber(phone, tsActId);
    tmp.getUnionByPhoneData = getInfoByPhoneNumber;
    tmp.getInfoByUnionIdData = getInfoByUnionId;
    // 授权手机号
    let {
      phoneNumber,
      phoneSuccess
    } = getInfoByPhoneNumber;
    // 当前微信
    let {
      getPhoneNumber,
      unionSuccess
    } = getInfoByUnionId;
    let {
      invited
    } = tsInfo;
    tmp.canRegister = (() => {
      if (getPhoneNumber) {
        return getPhoneNumber === phoneNumber ? true : false;
      }
      return true;
    })();
    if (!!invited) {
      // 受邀用户
      if (!phoneSuccess && !unionSuccess) {
        messageModalCode = "SUCCESS_JOIN_NEXT";
      } else if (
        !phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        // 授权手机号非会员 ， unionid有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NOT_MEMBER";
      } else if (
        phoneSuccess &&
        unionSuccess &&
        getPhoneNumber &&
        getPhoneNumber !== phoneNumber
      ) {
        // 授权手机号是会员 ， unionid有手机号且手机号和授权手机号不一致
        messageModalCode = "FAIL_NO_ID";
      } else if (
        !unionSuccess ||
        !getPhoneNumber ||
        (unionSuccess && getPhoneNumber == phoneNumber)
      ) {
        // union-id没有手机号 或 union-id有手机号且手机号和授权手机号一致
        messageModalCode = "SUCCESS_BIND_NEXT";
      }
    } else {
      if (!!phoneSuccess) {
        messageModalCode = "AUTH_NOT_INVITED_OLD_MEMBER";
      } else {
        messageModalCode = "AUTH_NOT_INVITED_NEW_MEMBER";
      }
    }
  } catch (error) {
    // console.error("getTargetSaleStatus error:", error);
  }
  const result = {
    ...tmp,
    messageModalCode,
  };
  return result;
};

// ts活动中非受邀用户的正常流程
export const getTsCommonStatus = async (phone) => {
  let messageModalCode = MESSAGE_MODAL_NO_MATCHING_CODE;
  const tmp = {
    phoneNumber: phone,
  };
  try {
    const customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let getInfoByPhoneNumber = await getUnionByPhone(phone);
    let getInfoByUnionId = await getPhoneByUnion();
    tmp.getUnionByPhoneData = getInfoByPhoneNumber;
    tmp.getInfoByUnionIdData = getInfoByUnionId;
    let {
      phoneNumber,
      phoneSuccess
    } = getInfoByPhoneNumber;
    let {
      getPhoneNumber,
      unionSuccess
    } = getInfoByUnionId;
    if (!phoneSuccess && !unionSuccess) {
      messageModalCode = "SUCCESS_JOIN_MESSAGE";
    } else if (
      !phoneSuccess &&
      unionSuccess &&
      getPhoneNumber &&
      getPhoneNumber !== phoneNumber
    ) {
      // 授权手机号非会员 ， unionid有手机号且手机号和授权手机号不一致
      messageModalCode = "BIND_NOT_MEMBER_NO_ID";
    } else if (
      phoneSuccess &&
      unionSuccess &&
      getPhoneNumber &&
      getPhoneNumber !== phoneNumber
    ) {
      // 授权手机号是会员 ， unionid有手机号且手机号和授权手机号不一致
      messageModalCode = "BIND_MEMBER_NO_ID";
    } else if (
      !unionSuccess ||
      !getPhoneNumber ||
      getPhoneNumber == phoneNumber
    ) {
      // union-id没有手机号 或 union-id有手机号且手机号和授权手机号一致
      messageModalCode = "SUCCESS_BIND_MESSAGE";
    }
  } catch (error) {
    // console.error("getTsCommonStatus error:", error);
  }
  const result = {
    ...tmp,
    messageModalCode,
  };
  return result;
};

// 注册会员
export const registerUser = async (phone) => {
  const result = {
    registerSuccess: false,
    registerData: {},
    joinMemberSuccess: false,
    joinMemberData: {},
  };
  try {
    const accountInfo = uni.getAccountInfoSync();
    let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO) || "";
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
    let openId = userSpecialInfo.openid;
    let unionId = userSpecialInfo.unionId;
    let shareMemberCode = uni.getStorageSync("shareMemberCode") || "";
    let scene = uni.getStorageSync("sceneCode") || "";
    let tagShareCode;
    if (scene == 1007 || scene == 1008) {
      tagShareCode = uni.getStorageSync("tagShareCode");
    } else {
      tagShareCode = "";
    }
    let query = {
      appId: accountInfo.miniProgram.appId,
      avatarUrl: "https://100000063-1252208446.file.myqcloud.com/images/Davata.png",
      memberCode: shareMemberCode,
      merchantId: merchantInfo.cloudMerchantId,
      nickName: unionId.substring(unionId.length - 8),
      mobile: phone,
      openId: openId,
      unionId: unionId,
      loginToken: userSpecialInfo.loginToken || "",
      sceneCode: tagShareCode,
    };
    let value = getStorageIfNotExpired('registerParams')
    query = {
      ...query,
      ...value
    }
    const res = await api.registerUser({
      method: "POST",
      query,
    });
    if (res.code === 1000&&res.data&&res.data.jwt) {
      result.registerSuccess = true;
      result.registerData = res.data;
      const joinMemberRes = await joinMember(res.data.jwt);
      result.joinMemberSuccess = joinMemberRes.success;
      result.joinMemberData = joinMemberRes.data;
      commonSensors.commonSetProfile('customer', joinMemberRes.data)
    } else {
      tip.plainText(res.msg);
    }
  } catch (error) {
    // console.error("registerUser error:", error);
    tip.plainText("注册失败");
  }
  return result;
};

// 加入会员
export const joinMember = async (jwt) => {
  const result = {
    success: false,
    data: {},
  };
  try {
    const query = {
      memberChannelType: "WechatMP",
    };
    const res = await api.memberActive({
      method: "PUT",
      header: {
        jwt: jwt,
      },
      query,
    });
    if (res.code == 1000) {
      // 入会成功后重新获取用户信息
      commonFunction.commonLoginNew().then(() => {
        commonFunction.getMemberDetailNew().then((res) => {
          commonSensors.commonSetProfile('member', res.data)
          // commonSensors.loginWithKey(res.data.id)
        }).catch((err) => {})
        updatePolicyStatus();
      });
      result.success = true;
      result.data = res.data;
    }
  } catch (error) {
    // console.error("joinMember error:", error);
  }
  return result;
};
export const getStorageIfNotExpired = (key) => {
  const values = uni.getStorageSync(key)
  if (values) {
    const now = new Date().getTime();
    if (values.expireTime > now) {
      // 如果没有过期，返回数据
      return values.value;
    } else {
      // 数据已过期，清除
      uni.removeStorageSync(key);
      return {};
    }
  }

};
